package com.example.teachmvandroidchart.ui

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.android.frame.mvp.CommonBaseActivity
import com.android.util.threadPool.ThreadPoolManager
import com.example.teachmvandroidchart.R
import com.example.teachmvandroidchart.databinding.ActivityTeachMainBinding
import com.example.teachmvandroidchart.mqtt.CreatClinent
import com.example.teachmvandroidchart.util.Constant
import com.example.teachmvandroidchart.util.Constant.Companion.CONNECT_FLAG
import com.example.teachmvandroidchart.util.Constant.Companion.SUBSCRIBE
import com.example.teachmvandroidchart.util.Constant.Companion.SUBSCRIBE_FLAG
import com.example.teachmvandroidchart.util.SPTool
import com.example.teachmvandroidchart.util.State
import com.example.teachmvandroidchart.util.ToastUtil
import com.gyf.immersionbar.ImmersionBar
import java.util.concurrent.TimeUnit

/**
 * Created by dell on 2021/8/11.mvp
 */
class SettingActivity: CommonBaseActivity<ActivityTeachMainBinding>() {
    private var clinent = CreatClinent(this) // 实例化MQTT连接
    private var t_flag = false // 线程循环标志 - 消息面板
    private var ip = ""  //默认ip
    private var port = ""  //默认端口号
    private var driverid = ""
    private var productid = ""
    private var password = ""
    override fun handleView(savedInstanceState: Bundle?) {
        initData()
        intView()

    }

    private fun intView() {

        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)

    }

    override fun initListener() {

        //连接云
        binding.MqttConnect.setOnClickListener {
            Connet()
        }
        //订阅主题
        binding.Name.setOnClickListener {
            Subject()
        }
        //发送消息
        binding.ButtonBt.setOnClickListener {
            Send()
        }
        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
    }

    private fun initData() {
        binding.IP.setText(State.ip)
        binding.DriveID.setText(State.DriveID)
        binding.ProductID.setText(State.ProductID)
        binding.zhuti.setText(State.zhuti)
        binding.port.setText(State.port)
        binding.PWD.setText(State.password)
    }
    //发送
    private fun Send() {
        if (CONNECT_FLAG && SUBSCRIBE_FLAG) { //如果建立连接且订阅主题
            clinent.sendMqtt(SUBSCRIBE, binding.SendText.text.toString())
            ToastUtil.showToast("发送成功")
           // textView_set(1)
        } else {
            if (!CONNECT_FLAG)
                ToastUtil.showToast("请先建立连接")

            else if (!SUBSCRIBE_FLAG)
                ToastUtil.showToast("请先订阅主题")

            else ToastUtil.showToast("发送失败")
        }
    }

    //订阅
    private fun Subject() {
        if (CONNECT_FLAG) { //如果建立连接
            SUBSCRIBE = binding.zhuti.text.toString()
            SPTool.getInstance(this) !!.putString("zhuti", SUBSCRIBE)
            if (!SUBSCRIBE_FLAG) {
                clinent.subscribe(SUBSCRIBE)
                if (SUBSCRIBE_FLAG) {
                    t_flag = true //循环线程
                    //开启线程 对接收消息处理并更新消息view  只有在订阅主题后才能接收到来自主题的消息，所以放在此处
                    myThread()
                    binding.Name.setImageResource(R.mipmap.ic_subscription_yes)
                    ToastUtil.showToast("订阅成功")
                }
            } else {
                t_flag = false //退出循环线程
                clinent.unsubscribe(SUBSCRIBE) //退订主题
                binding.Name.setImageResource(R.mipmap.ic_subscription_on)

                ToastUtil.showToast("退订成功")
            }
        } else {

            ToastUtil.showToast("请先建立连接")
        }
    }

    // 连接
    private fun Connet() {
        var f_kq = false
        if (!CONNECT_FLAG) { //没有连接，建立连接
            driverid = binding.DriveID.text.toString()
            productid = binding.ProductID.text.toString()
            password = binding.PWD.text.toString()
            SPTool.getInstance(this) !!.putString("DriveID", driverid)
            SPTool.getInstance(this) !!.putString("ProductID", productid)
            SPTool.getInstance(this) !!.putString("password", password)
            if (driverid.isNotEmpty()) { //如果id不为空
                ip = binding.IP.text.toString()
                port = binding.port.text.toString()
                SPTool.getInstance(this) !!.putString("ip", ip)
                SPTool.getInstance(this) !!.putString("port", port)
                if (productid.isNotEmpty()) //如果用户名不为空
                    clinent.mqttClient(ip, port, driverid, productid, password)
                else {//为空则传入
                    clinent.mqttClient(ip, port, driverid)
                }
                f_kq = true
                //线程更新UI
                val thread = Thread(Runnable {
                    while (f_kq) {
                        if (CONNECT_FLAG) {//MQTT连接
                            val mMessage = Message.obtain()
                            mMessage.what = 1
                            mHandler.sendMessage(mMessage)
                            f_kq = false
                        } else {
                            val mMessage = Message.obtain()
                            mMessage.what = 2
                            mHandler.sendMessage(mMessage)
                        }
                        Thread.sleep(300)
                    }
                })
                thread.start()
            } else {
                ToastUtil.showToast("连接DriveID为空")
            }
        } else { // 已经连接，断开连接
            clinent.disconnect() //断开连接
            if (!CONNECT_FLAG) { //判断现在连接状态，如果处于断开连接状态
                binding.MqttConnect.setImageResource(R.mipmap.ic_mqtt_on)
                ToastUtil.showToast("断开连接")
                SUBSCRIBE_FLAG = false  // 订阅主题标志
                SUBSCRIBE = ""  //清空订阅主题内容
                binding.Name.setImageResource(R.mipmap.ic_subscription_on)
            } else {
                ToastUtil.showToast("断开连接失败")
            }
        }
    }
    // 创建一个Handler
    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    binding.MqttConnect.setImageResource(R.mipmap.ic_mqtt_yes)

                }
                2 -> {
                    binding.MqttConnect.setImageResource(R.mipmap.ic_mqtt_on)

                }
            }
        }
    }
    //线程
    fun myThread() {
        ThreadPoolManager.instance.getScheduledThreadPool().scheduleWithFixedDelay(Runnable {
            if (Constant.RECEIVE_FLAG) {  //如果接到消息
                Constant.RECEIVE_FLAG = false //将消息标志位置位
            }
        }, 0, 1, TimeUnit.SECONDS)
    }

    /***
     * 重写onDestroy方法
     * 销毁此界面前断开mqtt连接
     */
    override fun onDestroy() {
//        t_flag = false
//        if (CONNECT_FLAG)
//            clinent.disconnect()
        //我们自己的方法
        super.onDestroy()
    }

}
